# Log4Python 2011
from xml.dom.minidom import getDOMImplementation, parse
import datetime

LOGLEVEL_NONE = 1 << 0
LOGLEVEL_ERROR = 1 << 1
LOGLEVEL_NORMAL = 1 << 2
LOGLEVEL_VERBOSE = 1 << 3
LOGLEVEL_DEBUG = 1 << 4

class Appender(object):
    def __init__(self, level):
        self.__Level = level

    def doAppend(self, message, level):
        if(level > self.getLevel()):
            self.concreteAppend(message)

    def getLevel(self):
        return self.__Level

    def setLevel(self, level):
        self.__Level = level

    def concreteAppend(self, message):
        pass


class CsvAppender(Appender):
    def __init__(self, ruta, level):
        Appender.__init__(self, level)
        self._ruta = ruta

    def concreteAppend(self, mensaje):
        l = open(self._ruta, "ab")
        coma = ""
        for m in mensaje:
            l.write(coma + m)
            coma = ","
        l.write("\n")
        l.close()

class XmlAppender(Appender):
    def __init__(self, ruta, level):
        Appender.__init__(self, level)
        self._ruta = ruta

    def concreteAppend(self, mensaje):
        l = open(self._ruta, "ab")
        
        impl = getDOMImplementation()

        newDoc = impl.createDocument(None, "log", None)
        top_element = newDoc.documentElement
        
        item = newDoc.createElement("item")
        
        time = newDoc.createElement("time")
        now = datetime.datetime.now()
        timeValue = newDoc.createTextNode(str(now))
        time.appendChild(timeValue)
        
        priority = newDoc.createElement("priority")
        priorityValue = newDoc.createTextNode("DEBUG")
        priority.appendChild(priorityValue) 
        
        category = newDoc.createElement("category")
        categoryValue = newDoc.createTextNode("c1 [__init__]")
        category.appendChild(categoryValue)
        
        message = newDoc.createElement("message")
        messageValue = newDoc.createTextNode(mensaje)
        message.appendChild(messageValue)
        
        item.appendChild(time)
        item.appendChild(priority)
        item.appendChild(category)
        item.appendChild(message)
        top_element.appendChild(item)
        
        newDoc.writexml(l,"", "\t", "\n")

        l.write("\n")
        l.close()


if __name__ == "__main__":
    appenders = [CsvAppender("file1.txt", LOGLEVEL_NONE), XmlAppender("file2.txt", LOGLEVEL_NONE)]
    for a in appenders:
        a.doAppend("Probando los mensajes del Log", LOGLEVEL_NORMAL)
